package com.sunshine.ssm.controller.userInfo;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.sunshine.ssm.entity.UserInfo;
import com.sunshine.ssm.ftppool.client.FTPClientHelper;
import com.sunshine.ssm.service.IUserInfoService;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by WeiHong on 2016/12/6.
 */
@Controller
@RequestMapping(value = "userInfo")
public class UserInfoController {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserInfoController.class);

    @Resource
    private IUserInfoService userInfoService;

    @Resource
    private FTPClientHelper ftpClientHelper;

    /*@Resource
    private FtpClientTemplate template;*/

    @RequestMapping("index/{view}")
    public ModelAndView index(@PathVariable("view") String view) {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("/users/" + view);
        return mv;
    }

    /**
     * @param info
     * @param page easyui datagird 分页传过来的当前页
     * @param rows easyui datagird 分页传过来的每页显示的行数
     * @return
     */
    @RequestMapping(value = "getUserInfo")
    @ResponseBody
    public Object getUserInfo(UserInfo info, int page, int rows, @CookieValue(value = "cookieTest", required = false) String cookieTest,
                              @CookieValue(value = "JSESSIONID", required = false) String JSESSIONID,
                              HttpServletRequest request, HttpServletResponse response) {
        //创建分页对象，并初始化当前页，和每页显示的行数
        Page<UserInfo> pageUI = new Page<>(page, rows);
        //定义返回查询数据
        Map<String, Object> data = new HashMap<>();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        UserInfo userInfo = new UserInfo();
        //解决查询条件，不输入时属性为 "" 导致查询不出结果
        if (info.getId() != null && !"".equals(info.getId())) {
            userInfo.setId(info.getId());
        }
        if (info.getUserName() != null && !"".equals(info.getUserName())) {
            userInfo.setUserName(info.getUserName());
        }
        try {
            EntityWrapper<UserInfo> wrapper = new EntityWrapper<>();
            wrapper.setEntity(userInfo);
            //设置根据id 排序， true 为升序，false为倒序
            wrapper.orderBy("id", false);
            Page<UserInfo> userInfoPage = userInfoService.selectPage(pageUI, wrapper);
            data.put("total", userInfoPage.getTotal());
            data.put("rows", userInfoPage.getRecords());
        } catch (Exception e) {
            LOGGER.error("getUserInfo error", e);
        }

        /*******cookie测试*******/
        Cookie[] cookies = request.getCookies();
        for (int i = 0; i < cookies.length; i++) {
            System.out.println(cookies[i].getName() + ":" + cookies[i].getValue());
        }
        System.out.println("--------------cookieTest：" + cookieTest + "--------------");
        System.out.println("--------------JSESSIONID：" + JSESSIONID + "--------------");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss S");
        Cookie cookie = new Cookie("cookieTest", sdf.format(new Date()));
        //保留7天
        cookie.setMaxAge(60 * 60 * 24 * 7);
        response.addCookie(cookie);

        /*******session测试*******/
        HttpSession session = request.getSession();
        session.getId();
        return data;
    }

    @RequestMapping("saveUserInfo")
    @ResponseBody
    public Object saveUserInfo(UserInfo info) {
        Map<String, String> reultMap = new HashMap<>();
        info.setPassword(new Md5Hash(info.getPassword()).toString());
        for (int i = 0; i < 10000; i++) {
            UserInfo userInfo = new UserInfo();
            userInfo.setUserName("aa" + i);
            userInfo.setPassword("aa" + i);
            try {
                if (userInfoService.insert(userInfo)) {
                    reultMap.put("result", "success");
                } else {
                    reultMap.put("result", "error");
                }
            } catch (Exception e) {
                reultMap.put("result", "error");
                LOGGER.error("保存用户失败！", e);
            }
        }

        return reultMap;
    }

    @RequestMapping("deleteUserInfo/{id}")
    @ResponseBody
    public Object deleteUserInfo(@PathVariable("id") int id) {
        Map<String, String> reultMap = new HashMap<>();
        try {
            if (userInfoService.deleteById(id)) {
                reultMap.put("result", "success");
            } else {
                reultMap.put("result", "error");
            }
        } catch (Exception e) {
            reultMap.put("result", "error");
            LOGGER.error("删除用户失败！", e);
        }
        return reultMap;
    }

   /* @RequestMapping("upload")
    public void upload() {
        BufferedInputStream bis = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(new File("D:\\图片视频\\xiaba-103589043.jpg")));
            String jpg = template.uploadFile(bis, "/data/ftp/erp/nfs/null/2018/12/25/", "jpg");
            System.out.println("jpg = " + jpg);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (null != bis) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }*/

    @RequestMapping("upload2")
    public void upload2() {
        InputStream inputStream = null;
        try {
            for (int i = 0; i < 1; i++) {
                inputStream = new FileInputStream(new File("D:\\图片视频\\xiaba-103589043.jpg"));
                String s = UUID.randomUUID().toString();
                boolean b = ftpClientHelper.storeFile("erp/nfs/null/2018/14/26/", inputStream,  s + ".jpg");
                System.out.println("b = " + b);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            IOUtils.closeQuietly(inputStream);
        }
    }

    @RequestMapping("down")
    public void down() {
        boolean b = ftpClientHelper.downloadFile("erp/nfs/beforeloan/2018/12/28/30a55ddd-f8cf-4a97-ac64-30e2cd34494a.jpg", "D:\\test\\aa.jpg");
        System.out.println("b = " + b);

    }

}
